package com.example.qihuibao.widget.dialog

import android.app.AlertDialog
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Global
import com.example.qihuibao.enum.ChannelStd
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.EnumUtils
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.view.CommonRecyclerView
import com.example.qihuibao.widget.view.EdittextWithText

/**
 *@author: cww
 *@desc:企业信息操作
 *@date: 5/16/23 10:58 AM
 */
class MealFeeUpdateDialog(val mealId:String, val feeId:String) : BaseDialogFragment(R.layout.dialog_meal_fee_update) {
    var modifing = false
    var selectChannelStd: ChannelStd? = null
    val mealFeeList = mutableListOf<Fee>()
    //
    val mealSetFeeList = mutableListOf<MealSetFee>()
    val empTypeList = mutableListOf<EmpType>()

    override fun initView() {
        mView?.findViewById<View>(R.id.iv_close)?.setOnClickListener { dismiss() }
        (activity as MainActivity).getMainViewModel().queryFees(ReqQueryFeesBean(Global.canteenId, mealId, feeId)).observe(this) {fee ->
            if (fee.RetCode == "0") {
                mView?.findViewById<TextView>(R.id.tv_CantID)?.text = "餐厅ID：${Global.canteenId}"
                mView?.findViewById<TextView>(R.id.tv_MealID)?.text = "餐别ID：$mealId"
                mView?.findViewById<TextView>(R.id.tv_FeeID)?.text = "收费标准ID：$feeId"
                mView?.findViewById<EdittextWithText>(R.id.et_feeName)?.setContent(fee.FeeName?:"")
                val channelStd = EnumUtils.getChannelStd("1")
                selectChannelStd = channelStd[0]
                val spChannelStd = mView?.findViewById<Spinner>(R.id.sp_ChannelStd)
                spChannelStd?.isEnabled = false
                spChannelStd?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, channelStd)
                spChannelStd?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectChannelStd = channelStd[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                mealSetFeeList.clear()
                if (!fee.MealSetFeeList.isNullOrEmpty()) {
                    mealSetFeeList.addAll(fee.MealSetFeeList!!)
                }
                mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetFeeList)?.init(
                    R.layout.item_text_with_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    mealSetFeeList,
                    {parent, pos ->
                        if (mealSetFeeList.isNotEmpty()) {
                            parent.findViewById<TextView>(R.id.tv_content).text = "套餐ID: ${mealSetFeeList[pos].MealSetID}\n" +
                                    "订餐第一份价格: ${mealSetFeeList[pos].OrderFee}\n" +
                                    "订餐第二份价格: ${mealSetFeeList[pos].OrderFee2}\n" +
                                    "订餐第三份后价格: ${mealSetFeeList[pos].OrderFee3}\n" +
                                    "现场第一份价格: ${mealSetFeeList[pos].SpotFee}\n" +
                                    "现场第二份价格: ${mealSetFeeList[pos].SpotFee2}\n" +
                                    "现场第三份后价格: ${mealSetFeeList[pos].SpotFee3}"
                        }
                    },
                    {
                        if (modifing) {
                            showMealSetFeeDialog(it, mealSetFeeList[it])
                        }
                    },
                    {pos, itemView ->
                        if (modifing) {
                            itemView.findViewById<TextView>(R.id.tv_delete).visibility =
                                if (itemView.findViewById<TextView>(R.id.tv_delete).visibility == View.VISIBLE) View.GONE else View.VISIBLE
                            itemView.findViewById<TextView>(R.id.tv_delete).setOnClickListener {
                                mealSetFeeList.removeAt(pos)
                                mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetFeeList)?.adapter?.notifyDataSetChanged()
                            }
                        }
                    }
                )
                empTypeList.clear()
                if (!fee.EmpTypeList.isNullOrEmpty()) {
                    empTypeList.addAll(fee.EmpTypeList)
                }
                mView?.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList)?.init(
                    R.layout.item_text_with_delete,
                    LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                    empTypeList,
                    {parent, pos ->
                        if (empTypeList.isNotEmpty()) {
                            parent.findViewById<TextView>(R.id.tv_content).text = "人员类型ID: ${empTypeList[pos].EmpTypeID}"
                        }
                    },
                    {
                        if (modifing) {
                            showEmpTypeDialog(it, empTypeList[it])
                        }
                    },
                    {pos, itemView ->
                        itemView.findViewById<TextView>(R.id.tv_delete).visibility = if (itemView.findViewById<TextView>(R.id.tv_delete).visibility == View.VISIBLE) View.GONE else View.VISIBLE
                        itemView.findViewById<TextView>(R.id.tv_delete).setOnClickListener {
                            empTypeList.removeAt(pos)
                            mView?.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList)?.adapter?.notifyDataSetChanged()
                        }
                    }
                )
                mView?.findViewById<View>(R.id.iv_add_mealset_fee)?.setOnClickListener {
                    showMealSetFeeDialog()
                }
                mView?.findViewById<View>(R.id.iv_add_empType)?.setOnClickListener {
                    showEmpTypeDialog()
                }
                //
                mView?.findViewById<View>(R.id.tv_modify)?.setOnClickListener {
                    modifing = !modifing
                    mView?.findViewById<TextView>(R.id.tv_modify)?.text = if (modifing) "取消" else "修改"
                    spChannelStd?.isEnabled = modifing
//                    spOrderMode?.isEnabled = modifing
                    mView?.findViewById<EdittextWithText>(R.id.et_feeName)?.enableContent(modifing)
                    mView?.findViewById<View>(R.id.iv_add_mealset_fee)?.visibility = if (modifing) View.VISIBLE else View.GONE
                    mView?.findViewById<View>(R.id.iv_add_empType)?.visibility = if (modifing) View.VISIBLE else View.GONE
//                    mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetlList)?.adapter?.notifyDataSetChanged()
//                    if (!modifing) {
//                        initView()
//                    }
                }
                mView?.findViewById<View>(R.id.tv_update)?.setOnClickListener {
//                    modifing = true
//                    mView?.findViewById<View>(R.id.tv_modify)?.performClick()
                    updateFees()
                }
            }else {
                activity?.toast("查看详情失败")
            }
        }
    }

    private fun showMealSetFeeDialog(index:Int=0, bean:MealSetFee? = null) {
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_add_mealset_fee, null)
        val dialogBuilder = AlertDialog.Builder(activity)
        dialogBuilder.setView(view)
        val dialog = dialogBuilder.show()
        //
        if (bean != null) {
            view.findViewById<EdittextWithText>(R.id.et_MealSetID).setContent(bean.MealSetID!!)
            view.findViewById<EdittextWithText>(R.id.et_OrderFee).setContent("${bean.OrderFee}")
            view.findViewById<EdittextWithText>(R.id.et_OrderFee2).setContent("${bean.OrderFee2}")
            view.findViewById<EdittextWithText>(R.id.et_OrderFee3).setContent("${bean.OrderFee3}")
            view.findViewById<EdittextWithText>(R.id.et_SpotFee).setContent("${bean.SpotFee}")
            view.findViewById<EdittextWithText>(R.id.et_SpotFee2).setContent("${bean.SpotFee2}")
            view.findViewById<EdittextWithText>(R.id.et_SpotFee3).setContent("${bean.SpotFee3}")
        }
        view.findViewById<View>(R.id.btn_cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<View>(R.id.btn_ok).setOnClickListener {
            if (view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_OrderFee).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_OrderFee2).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_OrderFee3).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_SpotFee).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_SpotFee2).getContent().isEmpty() ||
                view.findViewById<EdittextWithText>(R.id.et_SpotFee3).getContent().isEmpty()
            ) {
                activity?.toast("输入不能为空")
                return@setOnClickListener
            }
            if (bean != null) {
                mealSetFeeList.remove(bean)
            }
            for (item in mealSetFeeList) {
                if (item.MealSetID == view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent()) {
                    activity?.toast("已有相同ID")
                    return@setOnClickListener
                }
            }
            mealSetFeeList.add(index, MealSetFee(
                view.findViewById<EdittextWithText>(R.id.et_MealSetID).getContent(),
                view.findViewById<EdittextWithText>(R.id.et_OrderFee).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_OrderFee2).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_OrderFee3).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_SpotFee).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_SpotFee2).getContent().toInt(),
                view.findViewById<EdittextWithText>(R.id.et_SpotFee3).getContent().toInt()
            ))
            mView?.findViewById<CommonRecyclerView>(R.id.rv_MealSetFeeList)?.adapter?.notifyDataSetChanged()
            dialog.dismiss()
        }
    }

    private fun showEmpTypeDialog(index:Int=0, bean:EmpType? = null) {
        val view = LayoutInflater.from(activity).inflate(R.layout.dialog_add_emp_type, null)
        val dialogBuilder = AlertDialog.Builder(activity)
        dialogBuilder.setView(view)
        val dialog = dialogBuilder.show()
        //
        if (bean != null) {
            view.findViewById<EdittextWithText>(R.id.et_EmpTypeID).setContent(bean.EmpTypeID!!)
//            view.findViewById<EdittextWithText>(R.id.et_EmpTypeName).setContent("${bean.EmpTypeName}")
        }
        view.findViewById<View>(R.id.btn_cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<View>(R.id.btn_ok).setOnClickListener {
            if (view.findViewById<EdittextWithText>(R.id.et_EmpTypeID).getContent().isEmpty()
            ) {
                activity?.toast("输入不能为空")
                return@setOnClickListener
            }
            if (bean != null) {
                empTypeList.remove(bean)
            }
            for (item in empTypeList) {
                if (item.EmpTypeID == view.findViewById<EdittextWithText>(R.id.et_EmpTypeID).getContent()) {
                    activity?.toast("已有相同ID")
                    return@setOnClickListener
                }
            }
            empTypeList.add(index, EmpType(
                view.findViewById<EdittextWithText>(R.id.et_EmpTypeID).getContent()
            ))
            mView?.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList)?.adapter?.notifyDataSetChanged()
            dialog.dismiss()
        }
    }

    private fun updateFees() {
        val req  =ReqUpdateFeesBean(
            Global.canteenId,
            mealId,
            feeId,
            mView?.findViewById<EdittextWithText>(R.id.et_feeName)?.getContent()?:"",
            selectChannelStd?.value?:"1",
            mealSetFeeList,
            empTypeList
        )
        (activity as MainActivity).getMainViewModel().updateFees(req).observe(this) {
            activity?.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
        }
    }

}